<template>
  <div>
    <el-button style="margin-left: 10px" size="mini" type="success" @click="dialogVisible = true"
      >文件上传</el-button
    >

    <el-dialog title="请选择文件" :visible.sync="dialogVisible" width="400px">
      <el-upload
        multiple
        class="upload-demo"
        ref="upload"
        action="#"
        :limit="limitNumber"
        :on-exceed="exceed"
        :http-request="httpRequest"
        :file-list.sync="fileList"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="mini" type="primary">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitUpload" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      limitNumber: 10,
      dialogVisible: false,
      fileList: [],
    };
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
    },
    httpRequest(param) {
      const filename = param.file.name;
      let formData = new FormData(); //FormData 承载二进制数据
      formData.append('file', param.file);

      this.$Axios({
        method: 'post',
        url: 'https://jsonplaceholder.typicode.com/posts/',
        data: formData,
        headers: { 'Content-Type': 'multipart/form-data' },
      })
        .then((res) => {
          if (res.code == 200) {
            // this.queryFileList();
          } else {
            return Promise.reject();
          }
        })
        .catch((error) => {
          let i = this.fileList.indexOf(param.file);
          this.fileList.splice(i, 1);
          this.$message.warning(filename + '文件上传失败');
        });
    },
    exceed(files, fileList) {
      this.$message.error(`最多只能上传${this.limitNumber}个文件!`);
    },
  },
};
</script>

<style scoped lang="less">
/deep/.el-dialog {
  overflow: hidden;
  min-width: 400px !important;
}

/deep/.el-dialog__header {
  padding: 0px !important;

  background-color: #409eff;
  overflow: hidden;
  .el-dialog__title {
    font-size: 12px;
    margin-left: 15px;
    color: white !important;
  }

  .el-dialog__headerbtn {
    top: 4px;
    right: 10px;
    .el-dialog__close {
      color: white !important;
    }
  }
}
/deep/.el-dialog__body {
  padding: 10px !important;
}

/deep/.el-dialog__footer {
  padding: 10px;
}

/deep/ .el-upload__tip {
  margin-bottom: 7px !important;
}

/deep/.el-upload-list {
  max-height: 100px;
  overflow-y: auto;
}
</style>
